﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThirdServices.AlertModel.Analyzers;
using ThirdServices.AlertModel.Factory.BaseInterface;
using ThirdServices.AlertModel.Factory.Entities.DTO;
using ThirdServices.EarthquakeSettings;
using HtmlAgilityPack;
using System.Xml.Linq;
using System.Globalization;

namespace ThirdServices.AlertModel.Providers.Iris.Verifiers
{
    class IrisEarthquakeVerifier : IAlert
    {
        /// <summary>
        /// Get or set max count of events to return 
        /// </summary>
        public int PointsMax { get; set; }
        /// <summary>
        /// Get or set max latitude
        /// </summary>
        public double LatMax { get; set; }
        /// <summary>
        /// Get or set min latitude
        /// </summary>
        public double LatMin { get; set; }
        /// <summary>
        /// Get or set max longitude
        /// </summary>
        public double LonMax { get; set; }
        /// <summary>
        /// Get or set min longitude
        /// </summary>
        public double LonMin { get; set; }
        /// <summary>
        /// Method for checking alerts 
        /// </summary>
        /// <returns>Alerts</returns>
        public List<BaseAlert> CheckAlert()
        {
            List<EarthquakeData> earthquakeData = new List<EarthquakeData>();
            string url = AlertsLinks.IrisEarthquakeAlertLink(PointsMax, LatMax, LatMin, LonMax, LonMin);
            XDocument xDoc = XDocument.Load(url);
            foreach (XElement xe in xDoc.Descendants("event"))
            {
                try
                {
                    earthquakeData.Add(new EarthquakeData
                    {
                        Date = Convert.ToDateTime(xe.Attribute("date").Value, CultureInfo.InvariantCulture),
                        Depth = Convert.ToDouble(xe.Attribute("dkm").Value, CultureInfo.InvariantCulture),
                        Latitude = Convert.ToDouble(xe.Attribute("lat").Value, CultureInfo.InvariantCulture),
                        Longitude = Convert.ToDouble(xe.Attribute("lng").Value, CultureInfo.InvariantCulture),
                        Magnitude = Convert.ToDouble(xe.Attribute("mag").Value, CultureInfo.InvariantCulture),
                        Source = xe.Attribute("source").Value
                    });
                }
                catch (Exception ex) { break; }
            }
            var baseAlerts = EarthquakeAnalyser.AnalyseEarthquakeData(earthquakeData);
            return baseAlerts;
        }
    }
}
